#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- This is config utils - Python
# -- write or read config file
# -- Examples as follows
# configUtils = ConfigUtils();
# configUtils.writeConfig("dataFiles", r"D:\Temp");
# print(configUtils.readConfig("dataFiles"));
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2017年7月24日 14:32:33
# ----------------------------------------------------------

import os
from configparser import ConfigParser
from files.logs import Logger


class ConfigUtils(object):
    """
        初始化 Config\n
        调用类的路径不同，获取项目路径也不同\n
        projectPath is None --> os.path.abspath(".")
    """
    _log = Logger.log();

    def __init__(self, projectPath=os.path.abspath(".")):
        self.separator = os.path.sep;
        self.__confPath = self.separator + "resources" + self.separator + "application.conf";
        # ------------------------------------ 加载默认配置 ------------------------------------
        # 获取项目路径
        self.projectPath = projectPath;
        # 配置文件路径
        self.configFile = self.projectPath + self.__confPath;
        self._log.info("获取配置文件路径：%s", self.configFile)
        # 文件路径
        self.resources = self.readConfig("resources_path");
        # 文件绝对路径
        self.resourcesPath = self.projectPath + self.separator + self.resources;
        # 主题路径名称
        self.themePath = self.readConfig("theme_path");
        # 数据文件路径
        self.dataFiles = self.readConfig("data_files");

    # 读取配置文件
    def readConfig(self, option, section="application"):
        # 读取配置文件对象
        configParser = ConfigParser();
        configParser.read(self.configFile);
        self._log.info("读取配置文件：{} - {}".format(section, option));
        if option.strip().__len__() > 0:
            return configParser.get(section, option);

    # 写入配置文件
    def writeConfig(self, option, value=None, section="application"):
        if option.strip().__len__() > 0:
            # parser config object
            configParser = ConfigParser();
            configParser.read(self.configFile);
            # modify section the option value
            configParser.set(section, option, value);
            self._log.info("修改配置文件：{} - {} - {}".format(section, option, value));
            # write config file
            with open(self.configFile, "w+") as tempFile:
                configParser.write(tempFile);
        else:
            self._log.error("option is None");
